package com.fzd.code.account.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fzd.code.account.orm.model.Account;
import com.fzd.code.account.orm.model.AccountPriv;
import com.fzd.code.account.service.IAccountPrivService;
import com.fzd.code.account.service.IAccountService;
import com.fzd.code.auth.token.Authorization;
import com.fzd.code.common.Page;
import com.fzd.code.common.PageData;
import com.fzd.code.encrpty.EncrptyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2018-07-17
 */
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAccountPrivService accountPrivService;

    @GetMapping("/{accountId}")
    @Authorization
    public Account get(@PathVariable String accountId) throws Exception{
        return this.accountService.selectByMap(
                new HashMap<String,Object>(){
                    {this.put("account_id",accountId);}
                }
        ).get(0);
    }

    @PutMapping
    @Authorization
    public boolean update(Account account) throws Exception{
        if(StringUtils.isNotEmpty(account.getPassword())){
            account.setPassword(EncrptyUtil.md5(account.getPassword()));
        }
        return this.accountService.updateById(account);
    }

    @GetMapping
    @Authorization
    public PageData<Account> list(Page<Account> page){
        com.baomidou.mybatisplus.plugins.Page<Account> sqlPage = new com.baomidou.mybatisplus.plugins.Page<>();
        sqlPage.setCurrent(
                page.getOffset()%page.getLimit()>0
                    ?page.getOffset()/page.getLimit()+1
                    :page.getOffset()/page.getLimit()
        );
        if(sqlPage.getCurrent() == 0){
            sqlPage.setCurrent(1);
        }
        sqlPage.setSize(page.getLimit());
        this.accountService.selectPage(sqlPage,new EntityWrapper<>(page.getParam()));
        return new PageData<>(sqlPage.getTotal(),sqlPage.getRecords());
    }

    @GetMapping("/{accountId}/priv")
    @Authorization
    public List<AccountPriv> priv(@PathVariable String accountId){
        return this.accountPrivService.selectList(
            new EntityWrapper<>(new AccountPriv(){
                {this.setAccountId(accountId);}
            })
        );
    }

    @PostMapping
    public boolean save(Account account){
        return this.accountService.insert(account);
    }
}

